package com.lm.timewheel.ele;

public class TimeWheel {
    private TimeSlot[] slots;
    private int currentIndex = 0;
    private final int slotCount;
    private final long tickDuration;

    public TimeWheel(int slotCount, long tickDuration) {
        this.slotCount = slotCount;
        this.tickDuration = tickDuration;
        this.slots = new TimeSlot[slotCount];
        for (int i = 0; i < slotCount; i++) {
            slots[i] = new TimeSlot();
        }
    }

    public void addTask(Runnable task, long delay) {
        int slotIndex = (int) ((currentIndex + delay / tickDuration) % slotCount);
        slots[slotIndex].addTask(task);
    }

    public void tick() {
        TimeSlot slot = slots[currentIndex];
        for (Runnable task : slot.getTasks()) {
            task.run();
        }
        slot.clearTasks();
        currentIndex = (currentIndex + 1) % slotCount;
    }
}
